package com.stu.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author MI
 * @ClassName HttpPostXml.java
 * @createTime 2021年11月15日 18:04:00
 */
@Slf4j
public class HttpPostXml {
    public static void postXml(String url, String xmlStr) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);

        // 解决中文乱码问题
        StringEntity entity = new StringEntity(xmlStr, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/xml");
        method.setEntity(entity);
        HttpResponse result = httpClient.execute(method);
        if (result.getStatusLine().getStatusCode() == 200) {
            String str = "";
            try {
                str = EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8);
                System.out.println(str);
            } catch (Exception e) {
                log.error("post请求提交失败:" + url, e);
            }
        }

    }

    public static void main(String[] args) {
        String url = "http://localhost:9101/hello/xml/";
        String xmlStr = "<User><id>133</id><sex>男</sex><age>18</age></User>";
        try {
            postXml(url, xmlStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
